<template>
  <div class="floating-panel-layout">
    <!-- 浮动导航面板 -->
    <transition name="panel-slide">
      <div v-if="showPanel" class="floating-panel" :style="panelStyle">
        <div class="panel-header">
          <div class="panel-title">快速导航</div>
          <div class="panel-controls">
            <button class="control-btn" @click="toggleMinimize">
              <el-icon><Minus /></el-icon>
            </button>
            <button class="control-btn" @click="togglePin">
              <el-icon><Lock /></el-icon>
            </button>
            <button class="control-btn" @click="closePanel">
              <el-icon><Close /></el-icon>
            </button>
          </div>
        </div>

        <div class="panel-content">
          <!-- 快速搜索 -->
          <div class="search-section">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索功能或页面..."
              size="small"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <div v-if="searchResults.length > 0" class="search-results">
              <div
                v-for="result in searchResults"
                :key="result.path"
                class="search-result-item"
                @click="navigateTo(result.path)"
              >
                <el-icon><component :is="result.icon" /></el-icon>
                <span>{{ result.title }}</span>
              </div>
            </div>
          </div>

          <!-- 常用功能 -->
          <div class="quick-actions">
            <h4>常用功能</h4>
            <div class="action-grid">
              <div
                v-for="action in quickActions"
                :key="action.path"
                class="action-item"
                @click="navigateTo(action.path)"
              >
                <div class="action-icon" :style="{ background: action.color }">
                  <el-icon :size="20">
                    <component :is="action.icon" />
                  </el-icon>
                </div>
                <span class="action-name">{{ action.title }}</span>
              </div>
            </div>
          </div>

          <!-- 最近访问 -->
          <div class="recent-section">
            <h4>最近访问</h4>
            <div class="recent-list">
              <div
                v-for="item in recentItems"
                :key="item.path"
                class="recent-item"
                @click="navigateTo(item.path)"
              >
                <div class="recent-icon" :style="{ background: item.color }">
                  <el-icon :size="16">
                    <component :is="item.icon" />
                  </el-icon>
                </div>
                <div class="recent-info">
                  <span class="recent-title">{{ item.title }}</span>
                  <span class="recent-time">{{ item.time }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 系统状态 -->
          <div class="system-status">
            <h4>系统状态</h4>
            <div class="status-items">
              <div class="status-item">
                <el-icon><User /></el-icon>
                <span>在线用户: {{ onlineUsers }}</span>
              </div>
              <div class="status-item">
                <el-icon><Clock /></el-icon>
                <span>系统运行: {{ systemUptime }}</span>
              </div>
              <div class="status-item">
                <el-icon><TrendCharts /></el-icon>
                <span>今日订单: {{ todayOrders }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <!-- 浮动触发器 -->
    <div
      class="floating-trigger"
      :class="{ active: showPanel }"
      @click="togglePanel"
      @mousedown="startDrag"
    >
      <el-icon :size="24"><Menu /></el-icon>
      <div v-if="hasNotification" class="notification-dot"></div>
    </div>

    <!-- 拖拽指示器 -->
    <div v-if="isDragging" class="drag-indicator" :style="dragIndicatorStyle">
      <div class="drag-preview">
        <el-icon><Menu /></el-icon>
        <span>拖拽移动</span>
      </div>
    </div>

    <!-- 主内容区 -->
    <main class="main-content">
      <router-view v-slot="{ Component }">
        <transition name="content-fade" mode="out-in">
          <component :is="Component" :key="$route.fullPath" />
        </transition>
      </router-view>
    </main>

    <!-- 快捷操作按钮组 -->
    <div class="quick-buttons">
      <button
        v-for="btn in quickButtons"
        :key="btn.action"
        class="quick-btn"
        :class="{ active: btn.active }"
        @click="handleQuickAction(btn.action)"
        :title="btn.title"
      >
        <el-icon :size="18">
          <component :is="btn.icon" />
        </el-icon>
      </button>
    </div>

    <!-- 上下文菜单 -->
    <div
      v-if="showContextMenu"
      class="context-menu"
      :style="contextMenuStyle"
      @click.stop
    >
      <div class="menu-item" @click="addToBookmarks">
        <el-icon><Star /></el-icon>
        <span>添加到书签</span>
      </div>
      <div class="menu-item" @click="sharePage">
        <el-icon><Share /></el-icon>
        <span>分享页面</span>
      </div>
      <div class="menu-item" @click="openInNewTab">
        <el-icon><CopyDocument /></el-icon>
        <span>在新标签页打开</span>
      </div>
      <div class="menu-divider"></div>
      <div class="menu-item" @click="refreshPage">
        <el-icon><Refresh /></el-icon>
        <span>刷新页面</span>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div
      v-if="showContextMenu"
      class="context-overlay"
      @click="closeContextMenu"
    ></div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, markRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Menu, Search, Minus, Lock, Close, User, Clock, TrendCharts,
  HomeFilled, ShoppingCart, Box, Money, UserFilled, DataBoard,
  Setting, Document, Calendar, Star, Share, CopyDocument, Refresh,
  Bell, Setting as SettingIcon, HelpFilled
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 面板状态
const showPanel = ref(false)
const isMinimized = ref(false)
const isPinned = ref(false)
const panelPosition = ref({ x: 20, y: 20 })
const panelSize = ref({ width: 320, height: 500 })
const isDragging = ref(false)
const dragStart = ref({ x: 0, y: 0 })

// 搜索功能
const searchKeyword = ref('')
const searchResults = ref([])

// 上下文菜单
const showContextMenu = ref(false)
const contextMenuStyle = ref({})

// 系统数据
const onlineUsers = ref(156)
const systemUptime = ref('2天 14小时')
const todayOrders = ref(89)
const hasNotification = ref(true)

// 快速操作
const quickActions = ref([
  {
    path: '/dashboard',
    title: '首页',
    icon: markRaw(HomeFilled),
    color: '#409eff'
  },
  {
    path: '/sales',
    title: '销售',
    icon: markRaw(ShoppingCart),
    color: '#67c23a'
  },
  {
    path: '/inventory',
    title: '库存',
    icon: markRaw(Box),
    color: '#e6a23c'
  },
  {
    path: '/finance',
    title: '财务',
    icon: markRaw(Money),
    color: '#f56c6c'
  },
  {
    path: '/member',
    title: '会员',
    icon: markRaw(UserFilled),
    color: '#909399'
  },
  {
    path: '/reports',
    title: '报表',
    color: markRaw(DataBoard),
    color: '#9c27b0'
  }
])

// 最近访问
const recentItems = ref([
  {
    path: '/dashboard',
    title: '数据概览',
    icon: markRaw(HomeFilled),
    color: '#409eff',
    time: '2分钟前'
  },
  {
    path: '/sales',
    title: '销售管理',
    icon: markRaw(ShoppingCart),
    color: '#67c23a',
    time: '15分钟前'
  },
  {
    path: '/reports',
    title: '财务报表',
    icon: markRaw(DataBoard),
    color: '#9c27b0',
    time: '1小时前'
  }
])

// 快捷按钮
const quickButtons = ref([
  {
    action: 'notifications',
    icon: markRaw(Bell),
    title: '通知中心',
    active: false
  },
  {
    action: 'settings',
    icon: markRaw(SettingIcon),
    title: '设置',
    active: false
  },
  {
    action: 'help',
    icon: markRaw(HelpFilled),
    title: '帮助',
    active: false
  }
])

// 计算属性
const panelStyle = computed(() => ({
  left: panelPosition.value.x + 'px',
  top: panelPosition.value.y + 'px',
  width: panelSize.value.width + 'px',
  height: isMinimized.value ? '60px' : panelSize.value.height + 'px',
  zIndex: isPinned.value ? 2000 : 1500
}))

const dragIndicatorStyle = computed(() => ({
  left: panelPosition.value.x + 'px',
  top: panelPosition.value.y + 'px'
}))

// 方法
const togglePanel = () => {
  showPanel.value = !showPanel.value
  if (showPanel.value) {
    hasNotification.value = false
  }
}

const toggleMinimize = () => {
  isMinimized.value = !isMinimized.value
}

const togglePin = () => {
  isPinned.value = !isPinned.value
  ElMessage.success(isPinned.value ? '面板已固定' : '面板已取消固定')
}

const closePanel = () => {
  showPanel.value = false
}

const startDrag = (e) => {
  if (isPinned.value) return
  isDragging.value = true
  dragStart.value = {
    x: e.clientX - panelPosition.value.x,
    y: e.clientY - panelPosition.value.y
  }
  document.addEventListener('mousemove', handleDrag)
  document.addEventListener('mouseup', stopDrag)
  e.preventDefault()
}

const handleDrag = (e) => {
  if (!isDragging.value) return
  panelPosition.value = {
    x: e.clientX - dragStart.value.x,
    y: e.clientY - dragStart.value.y
  }
  // 边界检查
  panelPosition.value.x = Math.max(0, Math.min(window.innerWidth - panelSize.value.width, panelPosition.value.x))
  panelPosition.value.y = Math.max(0, Math.min(window.innerHeight - panelSize.value.height, panelPosition.value.y))
}

const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
}

const handleSearch = () => {
  if (!searchKeyword.value) {
    searchResults.value = []
    return
  }
  
  const allItems = [
    ...quickActions.value,
    ...recentItems.value
  ]
  
  searchResults.value = allItems.filter(item =>
    item.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
  ).slice(0, 5)
}

const navigateTo = (path) => {
  router.push(path)
  closePanel()
  
  // 添加到最近访问
  const currentItem = [...quickActions.value, ...recentItems.value].find(item => item.path === path)
  if (currentItem) {
    const recentItem = {
      ...currentItem,
      time: '刚刚'
    }
    recentItems.value.unshift(recentItem)
    recentItems.value = recentItems.value.slice(0, 5)
  }
}

const handleQuickAction = (action) => {
  switch (action) {
    case 'notifications':
      ElMessage.info('通知中心功能')
      break
    case 'settings':
      router.push('/system/settings')
      break
    case 'help':
      ElMessage.info('帮助文档')
      break
  }
}

const showContextMenuHandler = (e) => {
  e.preventDefault()
  showContextMenu.value = true
  contextMenuStyle.value = {
    left: e.clientX + 'px',
    top: e.clientY + 'px'
  }
}

const closeContextMenu = () => {
  showContextMenu.value = false
}

const addToBookmarks = () => {
  ElMessage.success('已添加到书签')
  closeContextMenu()
}

const sharePage = () => {
  ElMessage.success('页面链接已复制')
  closeContextMenu()
}

const openInNewTab = () => {
  window.open(route.fullPath, '_blank')
  closeContextMenu()
}

const refreshPage = () => {
  window.location.reload()
}

// 生命周期
onMounted(() => {
  document.addEventListener('contextmenu', showContextMenuHandler)
})

onUnmounted(() => {
  document.removeEventListener('contextmenu', showContextMenuHandler)
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
})
</script>

<style scoped>
.floating-panel-layout {
  width: 100%;
  height: 100vh;
  position: relative;
  background: #f5f7fa;
  overflow: hidden;
}

/* 浮动面板 */
.floating-panel {
  position: fixed;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  transition: all 0.3s ease;
}

.panel-header {
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  color: white;
  cursor: move;
}

.panel-title {
  font-size: 16px;
  font-weight: 600;
}

.panel-controls {
  display: flex;
  gap: 8px;
}

.control-btn {
  width: 24px;
  height: 24px;
  border: none;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.control-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.panel-content {
  height: calc(100% - 50px);
  overflow-y: auto;
  padding: 16px;
}

.search-section {
  margin-bottom: 20px;
}

.search-results {
  margin-top: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
  max-height: 200px;
  overflow-y: auto;
}

.search-result-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  gap: 8px;
}

.search-result-item:hover {
  background: #f5f7fa;
}

.quick-actions h4,
.recent-section h4,
.system-status h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  margin-bottom: 20px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #f8f9fa;
}

.action-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.action-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-bottom: 8px;
}

.action-name {
  font-size: 12px;
  color: #606266;
  text-align: center;
}

.recent-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 20px;
}

.recent-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  gap: 8px;
}

.recent-item:hover {
  background: #f5f7fa;
}

.recent-icon {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.recent-info {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.recent-title {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.recent-time {
  font-size: 12px;
  color: #909399;
}

.status-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 0;
  font-size: 13px;
  color: #606266;
}

/* 浮动触发器 */
.floating-trigger {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 56px;
  height: 56px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
  z-index: 1000;
  color: white;
}

.floating-trigger:hover {
  transform: scale(1.1);
  box-shadow: 0 12px 32px rgba(102, 126, 234, 0.6);
}

.floating-trigger.active {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}

.notification-dot {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 12px;
  height: 12px;
  background: #f56c6c;
  border-radius: 50%;
  border: 2px solid white;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 拖拽指示器 */
.drag-indicator {
  position: fixed;
  pointer-events: none;
  z-index: 3000;
}

.drag-preview {
  background: rgba(102, 126, 234, 0.9);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  backdrop-filter: blur(10px);
}

/* 快捷按钮组 */
.quick-buttons {
  position: fixed;
  bottom: 100px;
  right: 30px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  z-index: 999;
}

.quick-btn {
  width: 40px;
  height: 40px;
  border: none;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  color: #606266;
}

.quick-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

.quick-btn.active {
  background: #409eff;
  color: white;
}

/* 上下文菜单 */
.context-menu {
  position: fixed;
  background: white;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  border: 1px solid #e4e7ed;
  z-index: 2000;
  min-width: 160px;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  gap: 8px;
  font-size: 14px;
  color: #303133;
}

.menu-item:hover {
  background: #f5f7fa;
}

.menu-divider {
  height: 1px;
  background: #e4e7ed;
  margin: 4px 0;
}

.context-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1999;
}

/* 主内容区 */
.main-content {
  width: 100%;
  height: 100vh;
  overflow-y: auto;
  padding: 20px;
}

/* 动画 */
.panel-slide-enter-active,
.panel-slide-leave-active {
  transition: all 0.3s ease;
}

.panel-slide-enter-from {
  opacity: 0;
  transform: translateX(100%) scale(0.9);
}

.panel-slide-leave-to {
  opacity: 0;
  transform: translateX(100%) scale(0.9);
}

.content-fade-enter-active,
.content-fade-leave-active {
  transition: all 0.3s ease;
}

.content-fade-enter-from {
  opacity: 0;
  transform: translateY(10px);
}

.content-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 响应式 */
@media (max-width: 768px) {
  .floating-panel {
    width: calc(100vw - 40px) !important;
    height: calc(100vh - 40px) !important;
    left: 20px !important;
    top: 20px !important;
  }
  
  .action-grid {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .quick-buttons {
    bottom: 100px;
    right: 20px;
  }
  
  .floating-trigger {
    bottom: 20px;
    right: 20px;
  }
}
</style>
